package cn.petplatform.petback.controller.ImgController;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author LNL
 * @date 2021/5/19 14:48
 */
@Controller
@Api(tags = "请求处理文件")
public class RequestImgController {


    @GetMapping("/static/upload/{id}")
    public void requestImg(HttpServletResponse response,
                           HttpServletRequest request,
                           @PathVariable("id") String id) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            String path = this.getClass().getClassLoader().getResource("").getPath().substring(1);
            String realPath = path + "/static/upload/"+id;
            fis = new FileInputStream(realPath);
            os = response.getOutputStream();

            int len;
            byte[] buffer = new byte[1024];
            while((len = fis.read(buffer)) != -1) {
                os.write(buffer,0,len);
            }
            os.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                os.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
